﻿using hundsun.mcapi;
using hundsun.t2sdk;

namespace QuantBox.XApi
{
    public class SubscribeCallback : UfxSubCallbackInterface
    {
        private readonly UfxClient _client;

        public SubscribeCallback(UfxClient client)
        {
            _client = client;
        }

        public override unsafe void OnReceived(CT2SubscribeInterface lpSub, int subscribeIndex, 
            void* lpData, int nLength, tagSubscribeRecvData lpRevData)
        {
            if (!_client.Connected) {
                return;
            }
            var unPacker = new CT2UnPacker(lpData, (uint)nLength);
            var error = unPacker.ReadErrorInfo();
            if (error != UfxErrorInfo.Ok) {
                _client.Spi.ProcessError(error.ToErrorField(nameof(SubscribeCallback)));
                return;
            }

            unPacker.SetCurrentDatasetByIndex(1);
            unPacker.First();
            OnCallback(lpSub, subscribeIndex, unPacker.GetChar("msgtype"), unPacker, 1);
        }

        public override void OnRecvTickMsg(CT2SubscribeInterface lpSub, int subscribeIndex, string tickMsgInfo)
        {

        }

        protected override void OnEntrustApproving(CT2SubscribeInterface lpSub, int subscribeIndex, sbyte msgType, UfxEntrustApproving[] data)
        {
            if (data.Length > 0) {
                _client.Spi.ProcessLog(new LogField(LogLevel.Info, $"OnEntrustApproving: {data[0].ThirdReff}"));
            }
        }

        protected override void OnEntrustCancelled(CT2SubscribeInterface lpSub, int subscribeIndex, sbyte msgType, UfxEntrustCancelled[] data)
        {
            if (data.Length > 0) {
                _client.dealProcessor.PostOrderRtn(msgType, data[0]);
            }
        }

        protected override void OnEntrustConfirmed(CT2SubscribeInterface lpSub, int subscribeIndex, sbyte msgType, UfxEntrustConfirmed[] data)
        {
            if (data.Length > 0) {
                _client.dealProcessor.PostOrderRtn(msgType, data[0]);
            }
        }

        protected override void OnEntrustReceived(CT2SubscribeInterface lpSub, int subscribeIndex, sbyte msgType, UfxEntrustReceived[] data)
        {
            if (data.Length > 0) {
                _client.dealProcessor.PostOrderRtn(msgType, data[0]);
            }
        }

        protected override void OnEntrustRejected(CT2SubscribeInterface lpSub, int subscribeIndex, sbyte msgType, UfxEntrustRejected[] data)
        {
            if (data.Length > 0) {
                _client.dealProcessor.PostOrderRtn(msgType, data[0]);
            }
        }

        protected override void OnEntrustTrade(CT2SubscribeInterface lpSub, int subscribeIndex, sbyte msgType, UfxEntrustTrade[] data)
        {
            if (data.Length > 0) {
                _client.dealProcessor.PostOrderRtn(msgType, data[0]);
            }
        }
    }
}